package cn.xi.service;

import cn.xi.checkItem.SecuritySpringService;
import cn.xi.pojo.Permission;
import cn.xi.pojo.Role;
import cn.xi.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SecuritySpring implements UserDetailsService {

    @Reference
    private SecuritySpringService securitySpringService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = securitySpringService.findSecurity(name);
        if (user==null){
            return null;
        }
        List<GrantedAuthority> list =new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        org.springframework.security.core.userdetails.User user1 =new org.springframework.security.core.userdetails.User(name,user.getPassword(),list);

        return user1;
    }
}
